<template>
  <div class="carousel">
    <div class="carousel-images">
      <img :src="images[currentIndex]" alt="Carousel Image" />
    </div>
    <div class="carousel-controls">
      <!-- <button @click="prevImage">Previous</button>
      <button @click="nextImage">Next</button> -->
    </div>
    <div class="carousel-indicators">
      <span
        v-for="(image, index) in images"
        :key="index"
        :class="{ active: index === currentIndex }"
        @click="setCurrentImage(index)"
      ></span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import swipper1 from '@/assets/images/swipper1.jpg';
import swipper2 from '@/assets/images/swipper2.jpg';
import swipper3 from '@/assets/images/swipper3.jpg';

const images = ref([swipper1, swipper2]);
const currentIndex = ref(0);
let autoplayInterval;

const nextImage = () => {
  currentIndex.value = (currentIndex.value + 1) % images.value.length;
};

const prevImage = () => {
  currentIndex.value = (currentIndex.value - 1 + images.value.length) % images.value.length;
};

const setCurrentImage = (index) => {
  currentIndex.value = index;
};

const startAutoplay = () => {
  autoplayInterval = setInterval(nextImage, 3000);
};

const stopAutoplay = () => {
  clearInterval(autoplayInterval);
};

onMounted(() => {
  startAutoplay();
});

onBeforeUnmount(() => {
  stopAutoplay();
});
</script>

<style scoped>
.carousel {
  position: relative; /* 确保轮播图位置 */
  width: 100%; /* 设置宽度 */
  min-height: 400px;
  /* max-width: 540px; */
  /* 设置最小高度 */
  overflow: hidden; /* 防止内容溢出 */
  z-index: 1; /* 确保在其他组件之上 */
}

.carousel-images img {
  width: 1420px; /* 设置宽度 */
  height: auto; /* 使图片填满容器 */
 /* object-fit: contain; 确保图片按比例填充 */
  margin: 0; /* 移除多余的边距 */
}

.carousel-controls {
  position: absolute;
  top: 50%;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.carousel-indicators {
  display: flex;
  justify-content: center;
  margin-top: 5px;
}

.carousel-indicators span {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: gray;
  margin: 0 5px;
  cursor: pointer;
}

.carousel-indicators span.active {
  background: black;
}
</style>